package mini.ideashare.cms.controller;

import com.alibaba.fastjson.JSON;
import mini.ideashare.cms.base.BaseResponse;
import mini.ideashare.cms.base.PageData;
import mini.ideashare.cms.manager.ArticleManager;
import mini.ideashare.cms.model.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lixiang
 * @CreateTime 2018/10/27
 **/
@Controller
public class ArticleController extends AbstractBaseController {
    @Autowired
    private ArticleManager articleManager;

    @GetMapping("/article/query")
    @ResponseBody
    public BaseResponse<PageData<Article>> queryArticle(Article article, Integer pageIndex , Integer pageSize){

        List<Article> articles = articleManager.queryArticle(article, pageIndex, pageSize);
        Long totalCount = articleManager.countArticle(article);

        pageIndex = pageIndex == null?1:pageIndex;
        pageSize = pageSize == null?20:pageSize;
        return  BaseResponse.assemblePageResponse(articles,totalCount,pageIndex,pageSize);
    }

    @PostMapping("/article/save")
    @ResponseBody
    public BaseResponse<String> saveItem(Article article){
        BaseResponse<String> baseResponse = new BaseResponse<>();
        articleManager.saveArticle(article);
        baseResponse.setData("OK");
        return  baseResponse;
    }

    @GetMapping("/article/list")
    @ResponseBody
    public String listItem(Article article, Integer pageNumber , Integer pageSize){

        Map<String,Object> map  = new HashMap<>();

        List<Article> articles = articleManager.queryArticle(article, pageNumber, pageSize);
        Long totalCount = articleManager.countArticle(article);
        map.put("total",totalCount);
        map.put("rows",articles);
        return JSON.toJSONString(map);
    }
    
    @GetMapping("/article/get")
    @ResponseBody
    public Article listItem(Article article){

        List<Article> articles = articleManager.queryArticle(article, 1, 1);
        if(articles!=null && articles.size()>0){
            return articles.get(0);
        }else{
            return new Article();
        }
    }

    @GetMapping("/article/delete")
    @ResponseBody
    public String delete(Long id){
        articleManager.deleteArticle(id);
        return "OK";
    }

}
